import os
import sys
from openpyxl import load_workbook
import openpyxl
from io import BytesIO
from copy import copy
from excel_file import Spreadsheet, Sheet, Cell
class ExcelParser(object):
    def __init__(self, file_path, extension):
        self.file_path = file_path
        if self.file_path is None:
            raise Exception("excel file should not be none")
        try:
            if isinstance(file_path, str):
                self._wb = load_workbook(file_path, data_only=True)
            elif isinstance(file_path, bytes):
                print("read from stream")
                self._wb = load_workbook(file_path, data_only=True)
        except Exception as err:
            raise Exception("read excel file error")
        self.operate_wb = copy(self._wb)
        self.sheet_names = self.operate_wb.get_sheet_names()
        self.ext = extension
        self.sheet_list = self.parser_sheet()
        print(self.sheet_list)
        import pdb;pdb.set_trace()
        # extension 当前为 xlsx
    def parser_sheet(self):
        if self.ext == "xlsx":
            return self.parser_xlsx_sheet()
        elif self.ext == "xls":
            return self.parser_xls_sheet()
        else:
            raise Exception("unsupport extension")
    
    def parser_xlsx_sheet(self):
        sheet_list = []
        for sheet_name in self.sheet_names:
            sheet = self.operate_wb[sheet_name]
            sheet_list.append(sheet)
        return sheet_list
    
    def parser_xls_sheet(self):
        pass
    
    def get_sheet_by_name(self, sheet_name):
        pass
    
    def get_sheet_by_index(self, index):
        pass
    
    
    def generate_spreadsheet(self) -> Spreadsheet:
        pass
    
    
if __name__ == "__main__":
    excel_parser = ExcelParser("test1.xlsx", "xlsx")
    sheet_list = excel_parser.sheet_list
    for sheet in sheet_list:
        print(sheet.title)
